import Vue from 'vue'
import Vuex from 'vuex'
import axios from './axios.js'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    isLogin: false,
  },
  mutations: {
    changeLoginStatus(state, { flag, token }) {  //登录退出 --》改变状态
      state.token = token
      state.isLogin = flag
      window.sessionStorage.setItem('token', token)
      return true
    },
  },
  actions: {
    loginIn({ commit }, ruleForm) {
      //登录
      return new Promise((resolve, reject) => {
        axios
          .post('/api/login', { ...ruleForm })
          .then((res) => {
            if (res.meta.status === 200) {
              resolve()
              // console.log(res)
              commit('changeLoginStatus', { flag: true, token: res.data.token })
            } else {
              reject()
            }
          })
          .catch(() => {
            reject()
          })
      })
    },
    logout({ commit }) {
      //退出登录
      return new Promise((resolve)=>{
        commit('changeLoginStatus', { flag: false, token: '' })
        resolve()
      })
    },
    
  },
})

export default store
